package com.greensam.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author: Machengrui
 * @Date: 2024/12/24 16:15
 */
public class PinyinUtil {

    /**
     * 获取汉语拼音格式
     */
    public static String getSimplePinYin(String src) {
        if (StringUtils.isBlank(src)) {
            return "";
        }
        char[] hz = src.toCharArray();
        //该数组用来存储
        String[] py;

        //存放拼音字符串
        StringBuilder pys = new StringBuilder();

        try {
            for (char c : hz) {
                //先判断是否为汉字字符
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    //将汉字的几种全拼都存到py数组中
                    py = PinyinHelper.toHanyuPinyinStringArray(c, getHanyuPinyinOutputFormat());
                    //取出改汉字全拼的第一种读音，第一个字母
                    if (py != null && py.length > 0) {
                        pys.append(py[0].charAt(0));
                    }
                } else {
                    //如果不是汉字字符，直接取出字符并连接到 pys 后
                    pys.append(c);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return pys.toString();
    }

    private static HanyuPinyinOutputFormat getHanyuPinyinOutputFormat() {
        //设置汉字拼音输出的格式
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        return format;
    }

    /**
     * 提取每个汉字的首字母
     *
     */
    public static String getPinYinHeadChar(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        StringBuilder convert = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            //提取汉字的首字母
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        return convert.toString().toUpperCase();
    }
}
